import { FastifyPluginAsync } from "fastify";
import { ObjectId } from "mongodb";
import { CommentDocument } from "../../../models/schemas";

const getCommentsRoutes: FastifyPluginAsync = async (
  fastify,
  opts,
): Promise<void> => {
  fastify.get(
    "/get-comments/:orderId",
    {
      schema: {
        params: {
          type: "object",
          required: ["orderId"],
          properties: {
            orderId: { type: "string" },
          },
        },
        querystring: {
          type: "object",
          properties: {
            page: { type: "string", default: "1" },
            pageSize: { type: "string", default: "20" },
          },
        },
        response: {
          200: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              data: {
                type: "object",
                properties: {
                  comments: {
                    type: "array",
                    items: {
                      type: "object",
                      properties: {
                        _id: { type: "string" },
                        orderId: { type: "string" },
                        parentId: { type: "string" },
                        content: { type: "string" },
                        author: { type: "string" },
                        isAdmin: { type: "boolean" },
                        createdAt: { type: "number" },
                        updatedAt: { type: "number" },
                        replies: {
                          type: "array",
                          items: {
                            type: "object",
                          },
                        },
                      },
                    },
                  },
                  pagination: {
                    type: "object",
                    properties: {
                      total: { type: "number" },
                      page: { type: "number" },
                      pageSize: { type: "number" },
                      totalPages: { type: "number" },
                    },
                  },
                },
              },
            },
          },
          400: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
            },
          },
          500: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
            },
          },
        },
      },
    },
    async (request, reply) => {
      const db = fastify.mongo.db;
      if (!db) {
        return reply.code(500).send({
          success: false,
          error: "数据库连接失败",
        });
      }

      const { orderId } = request.params as { orderId: string };
      const { page = "1", pageSize = "20" } = request.query as {
        page?: string;
        pageSize?: string;
      };

      try {
        // 验证订单是否存在
        const orderExists = await db.collection("orders").findOne({
          _id: new ObjectId(orderId),
        });

        if (!orderExists) {
          return reply.code(400).send({
            success: false,
            error: "订单不存在",
          });
        }

        const pageNum = parseInt(page, 10) || 1;
        const pageSizeNum = parseInt(pageSize, 10) || 20;
        const skip = (pageNum - 1) * pageSizeNum;

        // 获取顶级评论（没有parentId的评论）
        const pipeline = [
          {
            $match: {
              orderId: new ObjectId(orderId),
              parentId: { $exists: false },
            },
          },
          {
            $sort: { createdAt: -1 },
          },
          {
            $skip: skip,
          },
          {
            $limit: pageSizeNum,
          },
          {
            $lookup: {
              from: "comments",
              let: { commentId: "$_id" },
              pipeline: [
                {
                  $match: {
                    $expr: { $eq: ["$parentId", "$$commentId"] },
                  },
                },
                {
                  $sort: { createdAt: 1 },
                },
              ],
              as: "replies",
            },
          },
        ];

        const [comments, totalCount] = await Promise.all([
          db
            .collection<CommentDocument>("comments")
            .aggregate(pipeline)
            .toArray(),
          db.collection<CommentDocument>("comments").countDocuments({
            orderId: new ObjectId(orderId),
            parentId: { $exists: false },
          }),
        ]);

        // 转换ObjectId为字符串
        const formattedComments = comments.map((comment) => ({
          ...comment,
          _id: comment._id.toString(),
          orderId: comment.orderId.toString(),
          replies: (comment.replies as any[]).map((reply) => ({
            ...reply,
            _id: reply._id.toString(),
            orderId: reply.orderId.toString(),
            parentId: reply.parentId.toString(),
          })),
        }));

        return {
          success: true,
          data: {
            comments: formattedComments,
            pagination: {
              total: totalCount,
              page: pageNum,
              pageSize: pageSizeNum,
              totalPages: Math.ceil(totalCount / pageSizeNum),
            },
          },
        };
      } catch (error) {
        fastify.log.error(error);
        return reply.code(500).send({
          success: false,
          error: "服务器内部错误",
        });
      }
    },
  );
};

export default getCommentsRoutes;
